<template>
  <div>
    <el-card>
      <div id="containerElectricity"></div>
    </el-card>

    <!-- 查询框与数据展示 -->
    <el-card class="hidden" v-show="!isShowCard" @click="show">+</el-card>
    <el-card id="dataTable" v-show="isShowCard">
      <div id="short" @click="show">-</div>
      <el-cascader
        placeholder="选择查询省份"
        :options="cityOption"
        filterable
        @change="showValue"
      ></el-cascader>
      <!-- 数据表格 -->
      <el-table
        :data="electricityTableData"
        height="250"
        style="width: 100%"
        v-show="0 == activeValue"
      >
        <el-table-column prop="years" label="年份" width="180" />
        <el-table-column prop="total" label="总发电量" width="180" />
        <el-table-column prop="fire" label="火力发电量" width="180" />
        <el-table-column prop="water" label="水力发电量" width="180" />
      </el-table>
      <!-- 折线图 -->
      <div ref="lineChart" v-show="1 == activeValue" id="lineChart"></div>

      <!-- 饼图 -->
      <el-select
        v-model="year"
        placeholder="Select"
        @change="changeYear"
        v-show="2 == activeValue"
      >
        <el-option
          v-for="item in yearOption"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <div ref="pieChart" v-show="2 == activeValue" id="pieChart"></div>

      <!-- 数据展示方式 -->
      <div id="select">
        <span
          v-for="(i, index) in showOptions"
          class="options"
          :class="{
            isActive: activeValue == index,
            noActive: activeValue != index,
          }"
          @click="isShow(index)"
          >{{ i }}</span
        >
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  reactive,
  ref,
  onMounted,
  onActivated,
  onDeactivated,
  toRefs,
  watch,
  nextTick,
} from "vue";
import { shallowRef } from "@vue/reactivity";
import AMapLoader from "@amap/amap-jsapi-loader";
import { createRegion } from "@/tools/createRegion.js";
import { getElectricityData } from "@/networks/energy/electricity.js";
import { ElMessage } from "element-plus";
import axios from "axios";
import * as echarts from "echarts";
export default {
  name: "electricity",
  setup() {
    window._AMapSecurityConfig = {
      //注册安全密钥
      securityJsCode: "7a147469fc71afc2c2540196e2453b2b",
    };
    const map = shallowRef(null); //声明地图容器
    let cityArray = reactive([]);
    let isShowCard = ref(true);
    const cityOption = reactive([
      {
        value: "北京市",
        label: "北京市",
      },
      {
        value: "天津市",
        label: "天津市",
      },
      {
        value: "河北省",
        label: "河北省",
      },
      {
        value: "山西省",
        label: "山西省",
      },
      {
        value: "内蒙古自治区",
        label: "内蒙古自治区",
      },
      {
        value: "辽宁省",
        label: "辽宁省",
      },
      {
        value: "吉林省",
        label: "吉林省",
      },
      {
        value: "黑龙江省",
        label: "黑龙江省",
      },
      {
        value: "上海市",
        label: "上海市",
      },
      {
        value: "江苏省",
        label: "江苏省",
      },
      {
        value: "浙江省",
        label: "浙江省",
      },
      {
        value: "安徽省",
        label: "安徽省",
      },
      {
        value: "福建省",
        label: "福建省",
      },
      {
        value: "江西省",
        label: "江西省",
      },
      {
        value: "山东省",
        label: "山东省",
      },
      {
        value: "河南省",
        label: "河南省",
      },
      {
        value: "湖北省",
        label: "湖北省",
      },
      {
        value: "湖南省",
        label: "湖南省",
      },
      {
        value: "广东省",
        label: "广东省",
      },
      {
        value: "广西壮族自治区",
        label: "广西壮族自治区",
      },
      {
        value: "海南省",
        label: "海南省",
      },
      {
        value: "重庆市",
        label: "重庆市",
      },
      {
        value: "四川省",
        label: "四川省",
      },
      {
        value: "贵州省",
        label: "贵州省",
      },
      {
        value: "云南省",
        label: "云南省",
      },
      {
        value: "西藏自治区",
        label: "西藏自治区",
      },
      {
        value: "陕西省",
        label: "陕西省",
      },
      {
        value: "甘肃省",
        label: "甘肃省",
      },
      {
        value: "青海省",
        label: "青海省",
      },
      {
        value: "宁夏回族自治区",
        label: "宁夏回族自治区",
      },
      {
        value: "新疆维吾尔自治区",
        label: "新疆维吾尔自治区",
      },
    ]);
    let electricityData = null; //存储请求返回的电能数据
    // let electricityTableData = reactive([]); //存储用于表格显示的格式化电能数据
    // 构造地图
    function initMap() {
      if (map.value) {
        map.value.destroy();
      }
      AMapLoader.load({
        key: "2b45c6a7655404e69a9b856504d8625c", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      })
        .then((AMap) => {
          map.value = new AMap.Map("containerElectricity", {
            //设置地图容器id
            viewMode: "3D", //是否为3D地图模式
            zoom: 10, //初始化地图级别
            center: [117.301291, 31.844148], //初始化地图中心点位置
            mapStyle: "amap://styles/darkblue",
          });
          //导入地图插件
          AMap.plugin(
            ["AMap.ToolBar", "AMap.Geolocation", "AMap.DistrictSearch"],
            async function () {
              // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
              // map.value.addControl(new AMap.ToolBar());
              // 在图面添加定位控件，用来获取和展示用户主机所在的经纬度位置
              map.value.addControl(new AMap.Geolocation());
              //  createRegion("合肥市",map.value)//绘制行政区边界
              // console.log(cityArray[0]);
              createRegion(cityArray[0], map.value);

              // //点击地图显示区域
              // map.value.on("click", async function (e) {
              //   const lnglat = e.lnglat;
              //   try {
              //     const { data: city } = await axios.get(
              //       `https://restapi.amap.com/v3/geocode/regeo?key=f58766337111f56d9101db384fbea982&location=${lnglat.lng},${lnglat.lat}`
              //     );
              //     // console.log(city);

              //     map.value.clearMap();
              //     initMap();
              //     cityArray[0] = city.regeocode.addressComponent.province;
              //   } catch (err) {
              //     console.log(err);
              //   }
              // });
            }
          );
        })
        .catch((e) => {
          console.log(e);
        });
    }

    function show() {
      console.log(isShowCard.value);
      isShowCard.value = !isShowCard.value;
    }

    //生命周期
    onMounted(() => {
      // initMap();
    });

    onActivated(() => {
      initMap();
    });

    onDeactivated(() => {
      if (map.value) {
        map.value.clearMap();
        map.value.destroy();
      }
    });

    return {
      map,
      cityArray,
      cityOption,
      electricityData,
      initMap,
      isShowCard,
      show,
    };
  },
  data() {
    return {
      electricityTableData: [],
      showOptions: ["表格", "折线图", "饼图"],
      activeValue: 0,
      year: 2020, //饼图显示的年份
      yearOption: [
        { value: 2020, label: "2020年" },
        { value: 2019, label: "2019年" },
        { value: 2018, label: "2018年" },
        { value: 2017, label: "2017年" },
        { value: 2016, label: "2016年" },
        { value: 2015, label: "2015年" },
        { value: 2014, label: "2014年" },
        { value: 2013, label: "2013年" },
        { value: 2012, label: "2012年" },
      ], //年份选择器配置项
    };
  },
  methods: {
    async showValue(value) {
      this.cityArray[0] = value[0];
      // console.log(this.cityArray);
      this.map.destroy();
      this.initMap();
      try {
        let { data: res } = await getElectricityData({
          city: this.cityArray[0],
        });
        // console.log(res)
        this.electricityData = res;
        this.electricityTableData = createElectricityData(res);
        // console.log(this.electricityTableData);
        this.$nextTick(() => {
          if (this.activeValue == 1) {
            this.createLineChart(); //创建图表
          } else if (this.activeValue == 2) {
            this.createPieChart(this.year); //创建饼图
          }
        });

        // console.log(this.electricityTableData);
      } catch (err) {
        console.log(err);
      }

      function createElectricityData(data) {
        //格式化数据
        let years = Object.keys(data.total);
        // years.shift();
        // console.log(years)
        let result = [];
        for (let i = 1; i < years.length; i++) {
          let dataRow = {
            years: years[i],
            total: data.total[years[i]],
            water: data.water[years[i]],
            fire: data.fire[years[i]],
          };
          result.push(dataRow);
        }
        // console.log(result)
        return reactive(result);
      }
    },

    // 创建折线图
    createLineChart() {
      if (this.$refs.lineChart == null) {
        return;
      }
      echarts.dispose(this.$refs.lineChart); //先对DOM进行清理
      let myChart = echarts.init(this.$refs.lineChart);
      let total = [],
        fire = [],
        water = [],
        other = [];
      // console.log(this.electricityTableData)
      for (let i = 0; i < this.electricityTableData.length; i++) {
        total.unshift(this.electricityTableData[i].total - 0);
        fire.unshift(this.electricityTableData[i].fire - 0);
        water.unshift(this.electricityTableData[i].water - 0);
        other.unshift(total[0] - fire[0] - water[0]);
      }
      // console.log(total,fire,water)
      myChart.setOption({
        title: {
          text: "2012-2020年发电量",
        },
        legend: {
          data: ["总量", "火力发电量", "水力发电量", "其他发电量"],
        },
        tooltip: {
          trigger: "axis",
        },
        toolbox: {
          show: true,
          feature: {
            dataZoom: {
              yAxisIndex: "none",
            },
            dataView: { readOnly: false },
            magicType: { type: ["line", "bar"] },
            restore: {},
            saveAsImage: {},
          },
        },
        xAxis: {
          name: "年份",
          data: [2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020],
          type: "category",
          boundaryGap: false,
        },
        yAxis: {
          name: "发电量/亿千瓦时",
          type: "value",
        },
        series: [
          {
            name: "总量",
            data: total,
            type: "line",
          },
          {
            name: "火力发电量",
            data: fire,
            type: "line",
          },
          {
            name: "水力发电量",
            data: water,
            type: "line",
          },
          {
            name: "其他发电量",
            data: other,
            type: "line",
          },
        ],
      });
    },

    // 创建饼图
    createPieChart(year) {
      // console.log(this.electricityTableData);
      if (
        this.electricityTableData.length == 0 ||
        this.$refs.pieChart == null
      ) {
        return;
      }
      echarts.dispose(this.$refs.pieChart);
      const pieChart = echarts.init(this.$refs.pieChart);
      if (year == null) {
        return pieChart;
      }
      let pieData = [];
      for (let i in this.electricityTableData) {
        if (this.electricityTableData[i].years == year + "年") {
          pieData.push({
            value: this.electricityTableData[i].water - 0,
            name: "水力发电量",
          });
          pieData.push({
            value: this.electricityTableData[i].fire - 0,
            name: "火力发电量",
          });
          pieData.push({
            value:
              this.electricityTableData[i].total -
              this.electricityTableData[i].water -
              this.electricityTableData[i].fire,
            name: "其他发电量",
          });
        }
      }
      // console.log(pieData);

      pieChart.setOption({
        title: {
          text: `${year}发电量各组分占比`,
          left: "center",
        },
        tooltip: {
          trigger: "item",
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        series: {
          name: `${this.year}年发电量`,
          type: "pie",
          radius: "50%",
          data: pieData,
        },
        legend: {
          orient: "vertical",
          left: "left",
          data: ["火力发电量", "水力发电量", "其他发电量"],
        },
      });
      return pieChart;
    },

    // 数据展示类型控制
    isShow(type) {
      this.activeValue = type;
      this.$nextTick(() => {
        if (this.activeValue == 1) {
          this.createLineChart();
        } else if (this.activeValue == 2) {
          this.createPieChart(this.year);
        }
      });
    },

    //年份选择改变时触发
    changeYear() {
      // console.log(this.year);
      this.createPieChart(this.year);
    },
  },

  computed: {},
  mounted() {},
};
</script>

<style lang="less" scoped>
#containerElectricity {
  width: calc(100vw - 200px);
  height: calc(100vh - 3rem);
  position: absolute;
  top: 3rem;
  left: 200px;
  z-index: 1;
}

#dataTable {
  // height: 100px;
  position: absolute;
  z-index: 2;
  top: 5rem;
  left: calc(1.5rem + 200px);
  #lineChart {
    height: 20rem;
    width: 50vw;
  }
  #pieChart {
    height: 20rem;
    width: 30vw;
  }
}

#select {
  width: 10rem;
  display: flex;
  // border: 1px solid black;
  .options {
    // height: 100%;

    width: 33%;
    text-align: center;
    font-size: 0.5rem;
    cursor: pointer;
  }
  .isActive {
    // background: #409EFF;
    border-left: 1px solid black;
    border-right: 1px solid black;
    border-bottom: 1px solid black;
    margin-top: 1px;
  }
  .noActive {
    background: white;
    border: 1px solid black;
  }
}

#short {
  position: absolute;
  right: 20px;
  font-size: 3rem;
  top: -10px;
  cursor: pointer;
}
.noShow {
  width: 10px !;
  height: 10px !;
}

.hidden {
  position: absolute;
  z-index: 2;
  top: 5rem;
  left: calc(1.5rem + 200px);
  font-size: 2rem;
  cursor: pointer;
}
</style>
